package com.xbongbong.paas.help.process;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessTaskEntity;
import com.xbongbong.paas.domain.entity.ext.FieldPermissionEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.dto.SummaryDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.pojo.vo.SummaryDataVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.InvoiceConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.help.InvoiceCommonHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/08/12 15:39
 */
@Component
public class ProcessSummaryHelp {

    private static final Logger LOG = LoggerFactory.getLogger(ProcessSummaryHelp.class);

    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private ProFormHelp proFormHelp;

    public SummaryDataVO getSummaryAndTitle(SummaryDataDTO summaryDataDTO) throws XbbException {
        SummaryDataVO summaryDataVO = new SummaryDataVO();
        try {
            PaasProcessDataEntity paasProcessDataEntity = summaryDataDTO.getPaasProcessDataEntity();
            PaasProcessTaskEntity paasProcessTaskEntity = summaryDataDTO.getPaasProcessTaskEntity();
            Map<String, UserEntity> userMap = summaryDataDTO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = summaryDataDTO.getDepartmentMap();
            summaryDataVO.setFlowStatusDesc(FlowStatusEnum.getMemoByType(paasProcessTaskEntity.getFlowStatus()));
            summaryDataVO.setFlowStatus(paasProcessTaskEntity.getFlowStatus());
            summaryDataVO.setFlowAddTime(paasProcessTaskEntity.getAddTime());
            FlowStatusEnum flowStatusEnum = FlowStatusEnum.getFlowStatusEnumByType(paasProcessTaskEntity.getFlowStatus());
            if (flowStatusEnum != null) {
                summaryDataVO.setColor(flowStatusEnum.getColor());
            }
            PaasFormExplainEntity paasFormExplainEntity = summaryDataDTO.getPaasFormExplainEntity();
            // 标签字段列表
            List<FieldAttrEntity> explainArray = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            if (explainArray == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainArray.size());
            // 数据字典需要转换下拉框
            if (Objects.equals(paasProcessDataEntity.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                explainArray = proFormHelp.handleExplainList(explainArray,paasProcessDataEntity.getBusinessType(),paasProcessDataEntity.getCorpid(),paasFormExplainEntity.getFormId());
            }
            for (FieldAttrEntity fieldAttrEntity : explainArray) {
                explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
            }
            JSONObject dataJsonObject = JSONObject.parseObject(paasProcessDataEntity.getData());
            // 设置创建者
            dataJsonObject.put(FieldTypeEnum.ADDTIME.getAlias(), paasProcessDataEntity.getAddTime());
            dataJsonObject.put(FieldTypeEnum.UPDATETIME.getAlias(), paasProcessDataEntity.getUpdateTime());
            dataJsonObject.put(FieldTypeEnum.SERIALNO.getAlias(), paasProcessDataEntity.getSerialNo());
            dataJsonObject.put(FieldTypeEnum.CREATORID.getAlias(), paasProcessDataEntity.getCreatorId());
            dataJsonObject.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasProcessDataEntity.getDepartmentId());

            //  获取用户和部门容器 解析paas的特殊数据 end
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            BeanUtil.copyProperties(summaryDataDTO, parseSingleRowDataDTO);
            BeanUtil.copyProperties(paasProcessDataEntity, parseSingleRowDataDTO);
            parseSingleRowDataDTO.setExplainMap(explainMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            parseSingleRowDataDTO.setIsProcess(true);
            // 兼容老数据，data没有ownId
            if (Objects.isNull(dataJsonObject.get(FieldTypeEnum.OWNERID.getAlias()))) {
                dataJsonObject.put(FieldTypeEnum.OWNERID.getAlias(), Collections.singletonList(paasProcessDataEntity.getOwnerId()));
            }
            JSONObject jsonObject = new JSONObject();
            JSONArray summaryJsonArray = new JSONArray();
            List<FieldPermissionEntityExt> fieldPermissionList = summaryDataDTO.getSummaryEntityList();
            boolean invoiceFlag = Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.INVOICE.getCode()) || Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
            if (invoiceFlag) {
                String originIdAttr = "";
                if (Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.INVOICE.getCode())) {
                    originIdAttr = InvoiceEnum.ORIGIN_ID.getAttr();
                } else if (Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode())) {
                    originIdAttr = PurchaseInvoiceEnum.ORIGIN_ID.getAttr();
                }
                if (dataJsonObject.containsKey(originIdAttr)) {
                    String originId = null;
                    if (Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.INVOICE.getCode())) {
                        originId = dataJsonObject.getString(InvoiceEnum.ORIGIN_ID.getAttr());
                    } else if (Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode())) {
                        originId = dataJsonObject.getString(PurchaseInvoiceEnum.ORIGIN_ID.getAttr());
                    }
                    if (Objects.nonNull(originId)) {
                        Long originIdLong = Long.valueOf(originId);
                        if (originIdLong > BasicConstant.ZERO) {
                            if (explainMap.size() > BasicConstant.ONE) {
                                Iterator<Map.Entry<String,FieldAttrEntity>> iterator =  explainMap.entrySet().iterator();
                                while (iterator.hasNext()){
                                    Map.Entry<String,FieldAttrEntity> it = iterator.next();
                                    FieldAttrEntity fieldAttrEntity = it.getValue();
                                    if (Objects.equals(fieldAttrEntity.getSaasAttr(), InvoiceEnum.TOTAL_MONEY.getSaasAttr())) {
                                        fieldAttrEntity.setAttrName(InvoiceConstant.REDSTRING + fieldAttrEntity.getAttrName());
                                    }
                                }
                            }

                            if (Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode()) || Objects.equals(paasProcessDataEntity.getBusinessType(),XbbRefTypeEnum.INVOICE.getCode())) {
                                InvoiceCommonHelp.getMinusAmountFormRedInvoice(dataJsonObject,null,originIdLong, BasicConstant.ZERO,paasProcessDataEntity.getBusinessType());
                            }
                        }
                    }
                }
            }

            if (Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode())) {
                //如果是回款单，则移除应收款、完成回款计划摘要
                List<String> removeAttrList = Arrays.asList(PaymentSheetEnum.PAYMENT.getAttr(), PaymentSheetEnum.PAYMENT_TASK.getAttr());
                for (FieldPermissionEntityExt s : fieldPermissionList) {
                    // 检索摘要
                    handleSummaryDataPojo(removeAttrList, summaryJsonArray, s, jsonObject, dataJsonObject, explainMap);
                }
            }  else if (Objects.equals(paasProcessDataEntity.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode())) {
                //如果是付款单，则移除付款计划摘要
                List<String> removeAttrList = Arrays.asList(PaySheetEnum.PAY_PLAN.getAttr());
                for (FieldPermissionEntityExt s : fieldPermissionList) {
                    // 检索摘要
                    handleSummaryDataPojo(removeAttrList, summaryJsonArray, s, jsonObject, dataJsonObject, explainMap);
                }
            } else {
                for (FieldPermissionEntityExt s : fieldPermissionList) {
                    handleSummaryDataPojo(null, summaryJsonArray, s, jsonObject, dataJsonObject, explainMap);
                }
            }
            parseSingleRowDataDTO.setDataJsonObject(jsonObject);
            ParseSingleRowDataVO parseSingleRowDataVO = formDataListAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
            if (Objects.isNull(parseSingleRowDataVO)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
            }
            LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
            linkResultDataVO.setUserMap(userMap);
            linkResultDataVO.setDepartmentMap(departmentMap);
            dataJsonObject = parseSingleRowDataVO.getResult();

            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            BeanUtil.copyProperties(paasProcessDataEntity, paasFormDataEntityExt);
            List<SummaryDataPoJo> summaryList = ExplainUtil.getSummaryList(summaryJsonArray, dataJsonObject, explainMap, paasFormDataEntityExt);

            summaryDataVO.setSummaryList(summaryList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询摘要数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return summaryDataVO;
    }

    /**
     * 处理摘要
     * @param removeAttrList 要移除的摘要字段list
     * @param summaryJsonArray 摘要
     * @param fieldPermissionEntityExt 字段权限实体
     * @author zcp
     * @since v1.0
     * @version v1.0
     * @update 2020/9/15 by zcp 要移除的可能是多个字段，改为list
     */
    private void handleSummaryDataPojo(List<String> removeAttrList, JSONArray summaryJsonArray, FieldPermissionEntityExt fieldPermissionEntityExt, JSONObject jsonObject, JSONObject dataJsonObject, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        if (CollectionsUtil.isNotEmpty(removeAttrList) && removeAttrList.contains(fieldPermissionEntityExt.getAttr())) {
            return;
        }
        // 检索摘要
        boolean summaryFlag = (fieldPermissionEntityExt.getSummary() != null && Objects.equals(fieldPermissionEntityExt.getSummary(), 1)) && (fieldPermissionEntityExt.getVisible() != null && Objects.equals(fieldPermissionEntityExt.getVisible(), 1));
        if (summaryFlag) {
            SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
            summaryDataPoJo.setFieldType(fieldPermissionEntityExt.getFieldType());
            summaryDataPoJo.setAttr(fieldPermissionEntityExt.getAttr());
            jsonObject.put(fieldPermissionEntityExt.getAttr(), dataJsonObject.get(fieldPermissionEntityExt.getAttr()));
            if (Objects.nonNull(explainMap.get(fieldPermissionEntityExt.getAttr())) &&
                    (Objects.equals(explainMap.get(fieldPermissionEntityExt.getAttr()).getFieldType(), FieldTypeEnum.LINK_BUSINESS_MULTI.getType()) || Objects.equals(explainMap.get(fieldPermissionEntityExt.getAttr()).getFieldType(), FieldTypeEnum.LINK_BUSINESS_SINGLE.getType()) || Objects.equals(explainMap.get(fieldPermissionEntityExt.getAttr()).getFieldType(), FieldTypeEnum.USER.getType()))) {
                jsonObject.put(explainMap.get(fieldPermissionEntityExt.getAttr()).getLinkedText(), dataJsonObject.get((explainMap.get(fieldPermissionEntityExt.getAttr()).getLinkedText())));
            }
            summaryJsonArray.add(summaryDataPoJo);
        } else {
            // 阶段流程id需要特殊保留下来，后面检索阶段版本需要
            Long stageProcessId = FastJsonHelper.getLongOrDefaultFromFormData(dataJsonObject, PaasStageEnum.STAGE_PROCESS_ID.getAttr(), BasicConstant.ZERO_LONG);
            if (!Objects.equals(stageProcessId, BasicConstant.ZERO_LONG)) {
                jsonObject.put(PaasStageEnum.STAGE_PROCESS_ID.getAttr(), dataJsonObject.get(PaasStageEnum.STAGE_PROCESS_ID.getAttr()));
            }
        }
    }
}
